﻿using System.Windows;
using System.Collections.Generic;
using FireFly;
using System.Collections;
using System.Windows.Controls;
using System;

namespace XAMLStylePad.ViewModels
{
    public class TemplateViewModel : XamlViewModelBase<FrameworkTemplate>
    {
        public TemplateViewModel(FrameworkTemplate template): base(template)
        {
        }

        #region overrides

       

        public override string DisplayName
        {
            get
            {
                return Model.GetType().Name;
            }
        }
        #endregion

        public object ResourceKey
        {
            get;
            set;
        }

        #region Component
        public DependencyObjectViewModel Component
        {
            get;
            private set;
        }
        #endregion

        #region RefreshCommand
        public static IRelayCommand RefreshCommand { get { return _RefreshCommand; } }
        static RelayCommand<TemplateViewModel> _RefreshCommand = new RelayCommand<TemplateViewModel>(context =>
        {
            context.ViewModel.ReloadComponent();
        }, 
        "TemplateViewModel.RefreshCommand");
        #endregion

        public override IRelayCommand SelectCommand
        {
            get
            {
                return new RelayCommand<TemplateViewModel>(context=>
                {
                    context.AppContext.SetObject(context.ViewModel.Model);
                    context.AppContext.PreviewPanel.SetTemplate(context.ViewModel);
                }, "TemplateViewModel.SelectCommand");
            }
        }

        public void ReloadComponent()
        {
            var newComponent = Model.LoadContent();
            if(Component == null || Component.IsSameModel(newComponent))
            {
                Component = new DependencyObjectViewModel(newComponent);
                OnPropertyChanged("Component");
            }
        }

        // command

        public override ICollection VisualChildren
        {
            get
            {
                if(Component == null)
                    ReloadComponent();
                
                return new IViewModel[] { Component };
                
            }
        }

        public object Data { get; set; }

        internal DependencyObject CreateControl()
        {
            var ctrl = Model.LoadContent();
            var element = ctrl as FrameworkElement;
            if(element != null && Data!=null) 
            {
                element.DataContext = Data;
            }
            return ctrl;
        }

        public Type GetDataType()
        {
            var dataTemplate = Model as DataTemplate;
            if(dataTemplate !=null)
                return (Type)dataTemplate.DataType;

            return null;
        }

    }
}
